package com.situ.studentmanagement.controller.api;

import com.situ.studentmanagement.Constants;
import com.situ.studentmanagement.OneDayCheckInfo;
import com.situ.studentmanagement.Utils;
import com.situ.studentmanagement.dao.CheckInfoMapper;
import com.situ.studentmanagement.dao.StudentMapper;
import com.situ.studentmanagement.model.CheckInfo;
import com.situ.studentmanagement.model.CheckLog;
import com.situ.studentmanagement.model.CheckLogArray;
import com.situ.studentmanagement.model.Student;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by niugao on 7/1/2016.
 */
@RestController
@RequestMapping("/api/student")
public class StudentController {
    @Autowired
    StudentMapper studentMapper;

    @Autowired
    private CheckInfoMapper checkLogMappler;

    //指定这个方法映射到哪个地址，这里没写地址，它会映射到类的地址。
    @RequestMapping(value = "/login")
    public Map login(HttpSession session,
                     @RequestParam("name") String name,
                     @RequestParam("password") String password) {
        Map map = new HashMap();
        try {
            //直接使用这个mapper即可，不用自己去创建了
            Student s = this.studentMapper.login(name, password);
            //把id保存到session中
            session.setAttribute(Constants.STUDENT_LOGIN_ATTR_ID, s.getId());
            map.put("result", 1);
            map.put("student", s);

        } catch (BindingException e) {
            map.put("result", 0);
            map.put("errorMsg", e.getLocalizedMessage());
        }catch (Exception e){
            map.put("result", 0);
            map.put("errorMsg", e.getLocalizedMessage());
        }

        return map;
    }

    //返回所有学生的信息
    @RequestMapping(value = "/getStudents")
    public Map getStudents(){
        Map map = new HashMap();

        try {
            //直接使用这个mapper即可，不用自己去创建了
            List<Student> students = this.studentMapper.getAllStudent();
            map.put("result", 1);
            map.put("students", students);
        } catch (BindingException e) {
            map.put("result", 0);
            map.put("errorMsg", e.getLocalizedMessage());
        }catch (Exception e){
            map.put("result", 0);
            map.put("errorMsg", e.getLocalizedMessage());
        }
        return map;
    }





    @RequestMapping(value = "/getCheckInfos")
    public Map getCheckInfos(HttpSession session,
                             @RequestParam("id") int student_id) {
        Map map = new HashMap();

        //获取考勤信息列表,默认就显示当前月（即最后一个月）的
        String firstDayOfMonth = Utils.getFirstDayOfMonthString(new Date());
        String lastDayOfMonth = Utils.getLastDayOfMonthString(new Date());

        //获取一个学生一月内的考勤信息
        List<CheckLog> checkLogs = checkLogMappler.getCheckLogForOneMonth(
                student_id, firstDayOfMonth, lastDayOfMonth);

        //从考勤信息列表产生OneDayCheckInfo列表
        List<OneDayCheckInfo> ret=new ArrayList();
        for(CheckLog cl :checkLogs){
            String curDay = Utils.getDateStringForDay(cl.getCheckInTime());
            String checkInTime = Utils.getDateStringForTime(cl.getCheckInTime());
            String checkOutTime = Utils.getDateStringForTime(cl.getCheckOutTime());
            ret.add(new OneDayCheckInfo(curDay,checkInTime,checkOutTime));
        }

        map.put("result", 1);
        map.put("checkInfos", ret);

        return map;
    }
    //1 实现提交文件的form
    //2 实现响应文件提交form action的方法
    //3 把文件内容保存到本地文件中，把数据库中student的头像文件名更新
    @RequestMapping(value = "/saveImg")
    public Map uploadHeadImg(Model model,
                             HttpSession session,
                             @RequestParam("head_img") MultipartFile file,
                             @RequestParam("id") int student_id) {
        Map map = new HashMap();
        String errMsg = null;

        //将上传的文件内容保存下来
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                String path = session.getServletContext().getRealPath("/WEB-INF/img");
                String file_name = "avatar/" + String.valueOf(student_id) + ".png";
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(path + "/" + file_name)));
                stream.write(bytes);
                stream.close();
                //把图片文件名设置到数据库中
                studentMapper.setHeadImgById(student_id, file_name);
            } catch (Exception e) {
                errMsg = e.getLocalizedMessage();
            }
        }

        map.put("result", 1);
        return map;
    }

    @RequestMapping(value = "/getLastCheckInfo", method = RequestMethod.GET)
    public Map getLastCheckInfo(Model model,
                                HttpSession session,
                                //上次刷新考勤信息时，最后一条信息的时间
                                //它是一个整数(应该是毫秒数)
                                @RequestParam(value = "last_check_time",required = false ) long time) {
        Map map = new HashMap();
        //从数据库中获取最后n条考勤信息，只要晚于时间time即可
        //如果time为0，则取比当前时间早10分钟的时间点
        try {
            String timeStr=null;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式，不显示毫秒
            if(time==0) {
                //如果time为0，则取比当前时间早10分钟的时间点
                Calendar calendar=Calendar.getInstance();
                calendar.setTime(new Date());
                //在当前时间基础上减10分钟
                calendar.add(Calendar.MINUTE,-10);
                timeStr = df.format(calendar.getTime());
            }else{
                Timestamp ts=new Timestamp(time);
                timeStr = df.format(ts);
            }
            //getCheckInfosAfterTime()对应的sql语句中，必须以时间进行排序
            List<CheckInfo> ci = studentMapper.getCheckInfosAfterTime(timeStr);
            map.put("result", 1);
//        List<CheckInfo> checkInfos=new ArrayList() ;
//        checkInfos.add(new CheckInfo("xiao ming",new Date()));
//        checkInfos.add(new CheckInfo("xiao wang",new Date()));
            map.put("checkInfos", ci);
        }catch(Exception e){
            String errMsg = null;
            map.put("result", 0);
            map.put("errMsg",errMsg);
        }
        return map;
    }

    //管理页面删除学生
    @RequestMapping("/deletStudent")
    public Map deletClass(Model model,
                          @RequestParam("id")int id) {
        studentMapper.deleteStudentById(id);
        Map map=new HashMap();
        map.put("deleId",id);
        return map;
    }
}
